package com.spzx.product.listeners;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import com.spzx.product.api.domain.vo.Category;
import com.spzx.product.domain.vo.CategoryExcelVo;

import com.spzx.product.service.ICategoryService;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@NoArgsConstructor
public class MyCategoryExcelListener extends AnalysisEventListener<CategoryExcelVo> {
    ICategoryService categoryService;
    //批处理
    List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>();

    public MyCategoryExcelListener(ICategoryService service) {

        this.categoryService = service;
    }

    @Override
    public void invoke(CategoryExcelVo categoryExcelVo, AnalysisContext analysisContext) {
        categoryExcelVoList.add(categoryExcelVo);
        if (categoryExcelVoList.size() >= 10) {
            List<Category> categories = categoryExcelVoList.stream().map(vo -> {
                Category category = new Category();
                BeanUtils.copyProperties(vo, category);
                return category;
            }).collect(Collectors.toList());
            categoryService.saveBatch(categories);
            categoryExcelVoList.clear();

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        List<Category> categories = categoryExcelVoList.stream().map(vo -> {
            Category category = new Category();
            BeanUtils.copyProperties(vo, category);
            return category;
        }).collect(Collectors.toList());
        categoryService.saveBatch(categories);
    }
}
